package com.itheima.controller.store;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.controller.BaseServlet;
import com.itheima.service.impl.store.PieAgeServiceImpl;
import com.itheima.service.store.PieAgeService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/store/pieage/*")
public class PieAgeServlet extends BaseServlet {
    PieAgeService pieAgeService = new PieAgeServiceImpl();
    protected void age(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Map<String, Object>> list = pieAgeService.findSexCount();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("ageCount",list);

        List<String> ageNames = new ArrayList<String>();
        for(Map<String,Object> m : list){
            String sex = (String) m.get("name");
            ageNames.add(sex);
        }
        map.put("age",ageNames);

        try {
             String json=new ObjectMapper().writeValueAsString(map);
            resp.setContentType("text/json;charset=utf-8");
            resp.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getage(HttpServletRequest req, HttpServletResponse resp){
        try {
            req.getRequestDispatcher("/WEB-INF/pages/store/pieage/age.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
